<template>
  <div class="rateForm" element-loading-text="表单加载中" element-loading-spinner="el-icon-loading" v-loading="loading">
    <Form :disabled="true" inline label-position="right" v-if="!isPreview && !isPCurl">
      <Form-item label="被评分对象" :label-width="120" v-if="isSystemInside">
        <Tooltip transfer max-width="800" :content="evaluationTargetTitle" placement="bottom" slot>
          <div class="object" @click="openApplyForm">{{ evaluationTargetTitle }}</div>
        </Tooltip>
      </Form-item>
      <Form-item label="推荐单位" :label-width="120" v-if="isSystemInside">
        <Input type="text" :value="evaluationTargetOrgName"></Input>
      </Form-item>
      <Form-item label="总分" :label-width="80">
        <Input type="text" v-model="total"></Input>
      </Form-item>
    </Form>
    <base-info
      :base-info-data="baseInfo"
      :create-form="createForm"
      :isPreview="isPreview"
      :isDetail="isDetail || status > 1"
      :isRateForm="true"
      :isPCurl="isPCurl"
    ></base-info>
    <div class="titBtn">
      <div class="rateTitle">
        <div class="block"></div>
        <div class="text">{{ rateTitle }}评分表</div>
      </div>
      <RPButton
        v-if="!isPreview && !isPCurl && stage !== 1"
        optType="create"
        type="info"
        text="查看历史评分"
        @click="showHistory"
      />
    </div>

    <rate-form
      v-if="showRateForm"
      ref="hotTableComponent"
      @setTotal="setTotal"
      :formData="formData"
      :cell="cell"
      :attributes="attributes"
      :read-only="status > 1 || isPreview || isPCurl"
      :isShared="isShared"
    ></rate-form>
    <!-- <div class="adjust">
      <div class="rateTitle">
        <div class="block"></div>
        <div class="text">调整项</div>
      </div>
      <div class="switchAdjust">
        <div class="text">是否增加调整项</div>
        <i-switch size="large" v-model="adjust.isAdjust" :disabled="row.status>1 || isPreview || isPCurl">
          <template #open>
            <span>On</span>
          </template>
          <template #close>
            <span>Off</span>
          </template>
        </i-switch>
      </div>
      <Form ref="adjustForm" :model="adjust" :rules="rules" v-if="adjust.isAdjust" :disabled="row.status>1 || isPCurl">
        <Form-item prop="add" label="加分项" :label-width="120">
          <InputNumber :min="0" v-model="adjust.add"></InputNumber>
        </Form-item>
        <Form-item prop="addCaption" label="加分说明" :label-width="120">
          <Row>
            <Col span="12">
              <Input v-model="adjust.addCaption"></Input>
            </Col>
          </Row>
        </Form-item>
        <Form-item prop="minus" label="减分项" :label-width="120">
          <InputNumber :max="0" v-model="adjust.minus"></InputNumber>
        </Form-item>
        <Form-item prop="minusCaption" label="减分说明" :label-width="120">
          <Row>
            <Col span="12">
              <Input type="text" v-model="adjust.minusCaption"></Input>
            </Col>
          </Row>
        </Form-item>
      </Form>
    </div> -->
    <!-- 抽屉 -->
    <Drawer :title="title" :width="1000" :closable="false" v-model="showDrawer">
      <ApplyForm
        v-if="showDrawer && DrawerType === 1"
        :id="evaluationTargetFormId"
        :recordId="evaluationTargetRecordId"
        :isPCurl="true"
        :PCurlGetData="true"
      ></ApplyForm>
      <history-rate
        v-if="showDrawer && DrawerType === 2"
        :id="row.id"
        :parentId="parentId"
        :stage="stage"
        :evaluationTargetTitle="this.evaluationTargetTitle"
      ></history-rate>
    </Drawer>
  </div>
</template>

<script>
import BaseInfo from '../../components/BaseInfo.vue'
import RateForm from './rateForm.vue'
import ApplyForm from '../applyForm/index.vue'
import HistoryRate from '../../components/HistoryRate.vue'
import formCenterApi from '@/api/formCenter'
import formDataApi from '@/api/formData'
import bpmpCenterApi from '@/api/bpmCenter.js'
import { getCodeFromName, getOrgFromCode } from '../../utils/index'
import { parseTreeData, addTotalScoreFormula } from './utils'
import { findNodePath } from '@/views/menuList/menus'
import { mapState } from 'vuex'
export default {
  components: { RateForm, BaseInfo, ApplyForm, HistoryRate },
  data() {
    return {
      loading: true,
      baseInfo: {
        tip: '',
        tipFile: [],
        org: '',
        time: '',
        contact: '',
        phone: '',
        email: '',
        attachment: []
      },
      createForm: {
        name: '',
        menu: [],
        remark: ''
      },
      formData: [],
      cell: [],
      adjust: {
        isAdjust: false,
        add: 0,
        addCaption: '',
        minus: 0,
        minusCaption: ''
      },
      sum: 0,
      fieldList: {}, // 后端字段转换
      showRateForm: false, // 解决handsontable无法更新data数组的问题
      type: 3,
      showDrawer: false,
      DrawerType: 1, // 1:被评分对象 2：查看历史评分
      title: '历史评分',
      attributes: {},
      rules: {
        add: [{ required: true, type: 'number', message: '请输入加分项', trigger: 'blur' }],
        addCaption: [{ required: true, message: '请输入加分说明', trigger: 'blur' }],
        minus: [{ required: true, type: 'number', message: '请输入减分项', trigger: 'blur' }],
        minusCaption: [{ required: true, message: '请输入减分说明', trigger: 'blur' }]
      },
      evaluationTargetFormId: '', // 被评分对象的表单id
      evaluationTargetRecordId: '', // 被评分对象的表单RecordId
      evaluationTargetTitle: '', // 被评分对象的标题
      evaluationTargetOrg: '', // 被评分对象的组织
      isSystemInside: false, // 是否对系统已有表单评分,用于控制是否显示被评分对象
      isShared: false, // 是否多人协同编辑
      parentId: '',
      stage: 1,
      status: 0,
      createBy: ''
    }
  },
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    isPCurl: {
      type: Boolean,
      default: false
    },
    rateTitle: {
      type: String,
      default: ''
    },
    initialFormData: {
      type: Object,
      default: () => {}
    },
    attrs: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapState(['loginData', 'orgList', 'menuList']),
    total() {
      //四舍五入
      const res = this.adjust.isAdjust ? this.sum + this.adjust.add + this.adjust.minus : this.sum
      console.log('res', res, this.attributes?.numberType)
      const accuracy = this.attributes?.numberType
      const score = Math.round(res * Math.pow(10, accuracy)) / Math.pow(10, accuracy)
      return score.toFixed(accuracy)
    },
    evaluationTargetOrgName() {
      return getOrgFromCode(this.orgList, this.evaluationTargetOrg)
    }
  },
  methods: {
    showHistory() {
      this.title = '历史评分'
      this.showDrawer = true
      this.DrawerType = 2
    },
    async openApplyForm() {
      this.title = '被评分对象表单'
      this.showDrawer = true
      this.DrawerType = 1
    },
    // 根据登录信息设置基本信息
    setBaseInfoFromLogin(userData) {
      const now = new Date()
      const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now
        .getDate()
        .toString()
        .padStart(2, '0')}`
      this.baseInfo.org = userData?.orgName || '-'
      if (this.row && this.row.updateTime) {
        this.baseInfo.time = this.row.updateTime.split(' ')[0]
      } else {
        this.baseInfo.time = formattedDate
      }
      this.baseInfo.contact = userData.userName
      this.baseInfo.phone = userData.mobile
      this.baseInfo.email = userData.email
    },
    // 根据返回的行数据设置基本信息
    setBaseInfoFromRowData(rowData) {
      let orgName = getOrgFromCode(this.orgList, rowData.org)
      if (orgName) {
        this.baseInfo.org = orgName
      } else {
        console.error('没有找到对应的组织信息')
        this.baseInfo.org = '-'
      }
      this.baseInfo.time = rowData.createTime?.split(' ')[0] || '-'
      this.baseInfo.contact = rowData.contact || '-'
      this.baseInfo.phone = rowData.phone || '-'
      this.baseInfo.email = rowData.email || '-'
      this.baseInfo.attachment = rowData.attachment || []
      // this.row.evaluationTargetTitle = rowData.evaluationTargetTitle
      // this.row.evaluationTargetOrgName = getOrgFromCode(this.orgList, rowData.evaluationTargetOrg) || '-'
    },
    handlePreviewData() {
      const parseData = parseTreeData(this.row.treeData[0])
      this.formData = parseData.result
      this.cell = parseData.cell
      this.attributes = this.attrs
      this.baseInfo = this.row.baseInfo
      this.showRateForm = true
    },
    async getFormData() {
      const res = await formCenterApi.formGetById({ id: this.row.id })
      this.fieldList = res.fieldList

      const recordData = await formDataApi.dataGetById({
        formId: this.row.id,
        recordId: this.row.recordId
      })
      this.evaluationTargetFormId = recordData.data.evaluationTargetFormId
      this.evaluationTargetRecordId = recordData.data.evaluationTargetRecordId
      this.evaluationTargetTitle = recordData.data.evaluationTargetTitle
      this.evaluationTargetOrg = recordData.data.evaluationTargetOrg
      this.parentId = recordData.data.parentId
      this.stage = recordData.data.stage
      this.status = recordData.data.status
      this.createBy = recordData.data.createBy
      const formData = Object.entries(recordData.data).reduce((acc, [key, value]) => {
        if (key.startsWith('fld')) {
          if (typeof value === 'string') {
            acc[key] = JSON.parse(value)
          } else {
            acc[key] = value
          }
        }
        return acc
      }, {})
      const value = Object.values(formData)
      return { formData: value, recordData: recordData.data, config: JSON.parse(res.config) }
    },
    async handleEditData(id) {
      this.setBaseInfoFromLogin(this.loginData)
      const res = await formCenterApi.getFormPage({ id })
      const config = JSON.parse(res.data.data.records[0].config)
      const obj = await this.getFormData()
      // todo -- 获取流程中的isShare是否为多人协同编辑和是否对已有表单评分
      const bpm = await bpmpCenterApi.getByRecordId({ recordId: this.row.recordId })
      this.isShared = bpm.data.data.isShared
      this.isSystemInside = bpm.data.data.isSystemInside
      const formData = obj.formData
      const recordData = obj.recordData
      if (formData.length) {
        // 第一次填写，后端还没有数据的时候
        if (this.status === 0) {
          this.formData = parseTreeData(config.treeData[0]).result || []
        } else {
          this.formData = formData[0]?.data || []
          this.adjust = formData[0]?.adjust || this.adjust
        }
        this.cell = parseTreeData(config.treeData[0]).cell
      } else {
        this.formData = parseTreeData(config.treeData[0]).data
      }
      this.attributes = config.treeData[0].attributes
      const nonLeafIndices = parseTreeData(config.treeData[0]).nonLeafIndices
      this.formData = addTotalScoreFormula(config.treeData[0], this.formData, nonLeafIndices, this.isShared)
      this.baseInfo.tip = config.baseInfo.tip
      this.baseInfo.tipFile = config.baseInfo.tipFile
      this.baseInfo.attachment = recordData.attachment || []
      this.setPageActions()
      this.showRateForm = true
    },

    async handleRecordData() {
      console.log('attrs', this.attrs)
      const obj = await this.getFormData()
      const bpm = await bpmpCenterApi.getByRecordId({ recordId: this.row.recordId })
      this.isShared = bpm.data.data.isShared
      this.isSystemInside = bpm.data.data.isSystemInside
      const formData = obj.formData
      const rowData = obj.recordData
      const config = obj.config
      this.setBaseInfoFromRowData(rowData)
      this.formData = formData[0]?.data || []
      this.adjust = formData[0]?.adjust || this.adjust
      const parseData = parseTreeData(config.treeData[0])
      this.attributes = config.treeData[0].attributes
      this.cell = parseData.cell
      const nonLeafIndices = parseData.nonLeafIndices
      this.formData = addTotalScoreFormula(config.treeData[0], this.formData, nonLeafIndices, this.isShared)
      this.setPageActions()
      this.showRateForm = true
    },

    setPageActions() {
      console.log('status', this.status)
      const btnList = [
        {
          text: '取消',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '保存',
          handle: this.saveForm
        },
        {
          text: '提交',
          theme: 'primary',
          handle: this.submit
        }
      ]
      const btnListForDetail = [
        {
          text: '取消',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '撤回',
          theme: 'primary',
          handle: this.handleWithdraw
        }
      ]
      if (this.status == 2 && this.createBy === this.loginData.userCode) {
        this.$emit('SetPageActions', btnListForDetail)
      } else if (this.status > 1 || this.isDetail) {
        this.$emit('SetPageActions', [])
      } else {
        this.$emit('SetPageActions', btnList)
      }
      // 撤回显示有问题，制表人能看到
      // this.$emit('SetPageActions', this.row.status = 2 && this.row.createBy===this.loginData.userCode ? btnListForDetail : btnList)
    },
    saveForm() {
      // 转换后端id
      const backendId = Object.keys(this.fieldList)
      const formData = {}
      formData[backendId[0]] = { data: this.formData, adjust: this.adjust }
      const params = {
        formId: this.row.id,
        recordId: this.row.recordId || '',
        data: {
          ...formData,
          ...this.baseInfo,
          score: this.total
        }
      }
      // 单独转换单位
      params.data.org = getCodeFromName(this.orgList, this.loginData.orgName)
      formDataApi.dataSaveOrUpdate(params).then(res => {
        if (res.data.code === 200) {
          this.$Message.success({
            content: '保存成功',
            duration: 2
          })
          // this.$emit('Close', true)
        }
      })
    },
    handleWithdraw() {
      this.$prompt('请输入撤回原因：', '撤回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputErrorMessage: '撤回原因不能为空',
        inputValidator: value => {
          if (!value) {
            return '撤回原因不能为空'
          }
        }
      }).then(res => {
        formDataApi.dataWithdraw({ recordId: this.row.recordId, undoReason: res.value }).then(res => {
          if (res.data.code === 200) {
            this.$emit('Close', true)
            this.$Message.success({
              content: '撤回成功',
              duration: 3
            })
          }
        })
      })
    },
    async submit() {
      const hotRef = this.$refs.hotTableComponent.$children[0].hotInstance
      const adjustRef = this.$refs.adjustForm
      const data = hotRef.getData() // 获取的是二维数组数据
      // 将formData的小计公式替换为数据
      data.forEach((item, index) => {
        const lastNumber = item[item.length - 1]
        this.formData[index].totalScore = lastNumber
      })
      const backendId = Object.keys(this.fieldList)[0]
      const formData = {
        [backendId]: { data: this.formData, adjust: this.adjust }
      }
      const pcUrl = this.getPcUrl()
      const params = this.getParams(pcUrl, formData)

      await this.confirmSubmission()

      if (await this.validateForms(hotRef, adjustRef)) {
        await this.submitData(params)
      }
    },
    getPcUrl() {
      let host = location.host
      if (host.includes('sit')) {
        host = 'crinfo-uat.test.crcloud.com'
      }
      return `https://${host}/form.html?type=formData&formType=${this.type}&id=${this.row.id}&recordId=`
    },

    getParams(pcUrl, formData) {
      const params = {
        formId: this.row.id,
        recordId: this.row.recordId || '',
        pcUrl,
        data: { ...formData, ...this.baseInfo, score: this.total }
      }
      params.data.org = getCodeFromName(this.orgList, this.loginData.orgName)
      return params
    },

    async confirmSubmission() {
      const result = await this.$confirm({
        content: '是否确认提交?'
      })
      return result
    },

    async validateForms(hotRef, adjustRef) {
      const hotValid = await new Promise(resolve => {
        hotRef.validateCells(valid => {
          if (!valid) {
            this.$Message.error({
              content: '请修改错误格式',
              duration: 2
            })
            resolve(false)
          } else {
            resolve(true)
          }
        })
      })

      let adjustValid
      if (this.adjust.isAdjust) {
        adjustValid = await new Promise(resolve => {
          adjustRef.validate(valid => {
            resolve(valid)
          })
        })
      } else {
        adjustValid = true
      }
      return hotValid && adjustValid
    },
    async submitData(params) {
      try {
        const res = await formDataApi.dataSubmit(params)
        if (res.data.code === 200) {
          this.$Message.success({
            content: '提交成功',
            duration: 2
          })
          this.$emit('Close', true)
        } else {
          // 处理提交失败的情况
          this.$Message.error({
            content: '提交失败',
            duration: 2
          })
        }
      } catch (error) {
        console.log('error', error)
        // 处理网络请求错误
        // this.$Message.error({
        //   content: '网络请求失败，请稍后重试',
        //   duration: 2
        // });
      }
    },
    async handleApproval() {
      await this.$store.dispatch('getMenuList')
      const res = await formCenterApi.formGetById({ id: this.row.id })
      const config = JSON.parse(res.config)
      const parseData = parseTreeData(config.treeData[0])
      this.formData = parseData.result
      this.cell = parseData.cell
      this.baseInfo.tip = config.baseInfo.tip
      this.baseInfo.tipFile = config.baseInfo.tipFile
      this.createForm.name = res.name
      this.createForm.remark = res.remark
      this.createForm.menu = findNodePath(this.menuList, res.menu)
      this.showRateForm = true
    },
    setTotal(sum) {
      if (typeof sum === 'number' && !isNaN(sum)) {
        this.sum = sum
      }
    },
    async initializeData() {
      if (Object.keys(this.loginData).length === 0) {
        await this.$store.dispatch('getLoginData')
      }
      try {
        // 检查并获取组织列表
        if (this.orgList.length <= 0) {
          await this.$store.dispatch('getOrgList')
        }

        // 处理预览模式
        if (this.isPreview) {
          this.handlePreviewData()
        }
        // 处理评分模式
        if (this.isEdit) {
          this.handleEditData(this.row.id)
          // this.setPageActions()
        }

        // 处理详情模式
        if (this.isDetail) {
          this.handleRecordData()
          // this.setPageActions()
        }
        // 审批页面
        if (this.isPCurl) {
          this.handleApproval()
        }
      } catch (error) {
        console.error('Error initializing data:', error)
        // 可以根据需要添加更多的错误处理逻辑，比如显示错误消息等
      } finally {
        this.loading = false
      }
    }
  },
  created() {
    this.initializeData()
    console.log('row', this.row, this.attributes)
  }
}
</script>

<style lang="less" scoped>
.rateForm {
  padding: 0 20px;
  .object {
    display: flex;
    width: 230px;
    height: 30px;
    margin-top: 4px;
    padding-left: 8px;
    border: 1px solid #c5c8ce;
    border-radius: 4px;
    background-color: #f8f8f9;
    color: #1890ff;
    align-items: center;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .rateTitle {
    display: flex;
    align-items: center;
    margin: 10px 0;
    .block {
      width: 6px;
      height: 28px;
      background: var(--primary-color);
      margin-right: 6px;
    }
    .text {
      font-weight: 600;
      font-size: 16px;
      color: var(--primary-color);
    }
  }
  .titBtn {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .adjust {
    .switchAdjust {
      display: flex;
      gap: 20px;
      margin: 20px 0;
      font-size: 14px;
      color: #676768;
    }
  }
}
</style>
